<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="author" content="beibei">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>9.10 课堂收</title>
    <link rel="stylesheet" href="./action.css">
</head>

<body>
    <div id="content">
        <div class="content">
            <img src="./images/1.jpg" class="current">


            <img src="./images/bounce.png" alt="" class="bounce">

            <textarea placeholder="点击输入你脑补的老师的吧啦吧啦"></textarea>
            <div class="textBox"></div>
        </div>

        <div class="bot">
            <span class="text"></span>

            <img src="./images/qrcode.png" alt="" class="qcode">
        </div>
    </div>

    <img src="./images/save.png" alt="" class="btn">

    <div class="botBox">
        <div class="box">
            <img src="./images/l1.jpg" alt="" class="option active">
            <img src="./images/l2.jpg" alt="" class="option">
            <img src="./images/l3.jpg" alt="" class="option">
            <img src="./images/l4.jpg" alt="" class="option">
            <img src="./images/l5.jpg" alt="" class="option">
            <img src="./images/l6.jpg" alt="" class="option">
            <img src="./images/l7.jpg" alt="" class="option">
            <img src="./images/l8.jpg" alt="" class="option">
            <div class="option add">
                <input type="file" accept="image/*" id="upload" />
            </div>
        </div>
    </div>

    <div class="popUp">
        <div class="mask"></div>
        <div id="bounce">
            <section id="s1">照片图库</section>
            <section style="border-top:solid 1px #ddd;" id="s2">拍照</section>
        </div>
    </div>

    <div class="isloading">
        <div class="mask"></div>
        <div class="loadimg">
            <img src="./images/loading.gif">
            <div>加载中...</div>
        </div>
    </div>
    <div class="toast"></div>

</body>
<script src="./js/jquery.min.js"></script>
<script src="./js/fastclick.js"></script>
<script src="./js/prefixfree.js"></script>
<script src="./js/pxtorem.js"></script>
<script src='./js/html2canvas.js'></script>
<script src='./js/canvas2image.js'></script>
<script src="./js/public.js"></script>
<script src="./js/exif.js"></script>
<script src="//cdn.bootcss.com/eruda/1.4.2/eruda.min.js"></script>
<script>eruda.init();</script>
<script>
    $(function () {
        FastClick.attach(document.body);
        var currentUploadUrl;
        var ua = navigator.userAgent.toLowerCase();
        var isAndroid = ua.indexOf('android') > -1 || ua.indexOf('linux') > -1; //android终端或者uc浏览器
        var isWeixin = ua.indexOf("micromessenger") > -1;
        var isQQ = ua.indexOf("qq") > -1;

        if (isAndroid && isQQ && !isWeixin) {
            $("input:file").attr("capture", "camera");
        };
        localStorage.removeItem("imgUrl");
        var tips = [
            "为我扶正一笔一划，伴我度过春秋冬夏",
            "晨曦余霞身影忙，三尺讲台写荣光",
            "思海暗暗，君乃灯塔永明北辰常在",
            "您今天怪怪的？是怪好看的",
            "您今天特别讨人喜欢和百看不厌",
            "有谣言说我想您，我要澄清一下，那不是谣言",
            "近朱者赤，近您者优秀",
            "感谢您，有生之年，欣喜相逢",
            "先送您一句教师节快乐！",
            "师者，传道授业解惑也",
            "再美的文字赞美您，都是苍白的",
            "人生这条路，感谢您的前方导航",
            "抱抱亲亲我亲爱的老师们",
            "敦敦教诲，念念不忘",
            "有你，我才能展翅高飞",
            "曾经我也立志，长大要当老师",
            "三克油，爱老虎油，爱密斯游",
            "老师，需要您笑一下，我的咖啡忘加糖了",
            "老师最近胖了吧,不然在我心里的分量怎么增加了",
            "老师呀，可爱不是长久之计，可您是",
            "一直要称呼您是因为你在我心上呀"
        ]

        if (localStorage.imageUrl) {
            location.reload();
        }

        var text = tips[random(21)];
        $("span.text").text(text);
        var pHeight = $("div.bot").height();
        var height = $("span.text").height();
        $("span.text").css("margin-top", (pHeight - height) / 2 + "px");

        connectWebViewJavascriptBridge(function (bridge) {

            bridge.registerHandler("getOperationResult", function (data) {
                currentUploadUrl = JSON.parse(data).imgUrl;

                $("img.current").attr("src", currentUploadUrl);
                getBase64(currentUploadUrl).then(function (base64Image) {
                    if (base64Image) {
                        $("img.current").attr("src", base64Image);
                    }
                })

            });

            if (isAndroid) {
                $("input").css("display", "none");

                $("div.option").click(function () {
                    showBounce();
                    $("img.option").removeClass("active");
                });

                $("#s1").click(function () {
                    //相册
                    hideBounce();
                    window.WebViewJavascriptBridge.callHandler('getNativeTools', { "type": 1 }, null)
                });

                $("#s2").click(function () {
                    hideBounce();
                    //相机
                    window.WebViewJavascriptBridge.callHandler('getNativeTools', { "type": 2 }, null)
                });

                $('.mask').click(function () {
                    hideBounce();
                });
            }
        })

        $("img.option").click(function () {
            $("img.option").removeClass("active");
            $(this).addClass("active");
            var src = $(this).attr("src");
            $("img.current").attr("src", src.replace("l", ""));
        })

        $("input").change(function (e) {
            $("img.option").removeClass("active");

            var file = e.target.files[0];
            upload(file);
        })

        //保存
        $("img.btn").click(function () {
            var message = $("textarea").val();
            var tHeight = $("textarea").height();

            if (message) {
                if (message.length > 20) {
                    return toast("最多不可超过20个字符", 200);
                }

                $("textarea").remove();
                $("div.textBox").text(message);
                var top = $("div.textBox").css("top").replace("px", "") * 1;
                var height = $("div.textBox").height();
                var offset = (tHeight - height) / 2;
                $("div.textBox").css("top", top + offset + "px");
            } else {
                //删除掉文本框和文本框背景图片；
                $("img.bounce").remove();
                $("textarea").remove();
            }

            $(".isloading").css("display", "block");

            toPicture();
        })

        function upload(file) {

            if (!file) {
                return;
            }

            var reader = new FileReader();
            var Orientation = null;

            EXIF.getData(file, function () {
                EXIF.getAllTags(this);
                Orientation = EXIF.getTag(this, 'Orientation');
                //return;
            });
            reader.onload = (function (file) {
                return function (e) {

                    var image = new Image();
                    image.crossOrigin = '';
                    image.src = e.target.result;
                    image.onload = function () {
                        var expectWidth = this.naturalWidth;
                        var expectHeight = this.naturalHeight;

                        if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                            expectWidth = 800;
                            expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                        } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
                            expectHeight = 1200;
                            expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                        }
                        var canvas = document.createElement("canvas");
                        var ctx = canvas.getContext("2d");
                        canvas.width = expectWidth;
                        canvas.height = expectHeight;
                        ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                        var base64 = null;
                        //修复ios
                        if (navigator.userAgent.match(/iphone/i)) {
                            //如果方向角不为1，都需要进行旋转 added by lzk
                            if (Orientation != "" && Orientation != 1) {
                                switch (Orientation) {
                                    case 6://需要顺时针（向左）90度旋转
                                        rotateImg(this, 'left', canvas);
                                        break;
                                    case 8://需要逆时针（向右）90度旋转
                                        rotateImg(this, 'right', canvas);
                                        break;
                                    case 3://需要180度旋转
                                        rotateImg(this, 'right', canvas);//转两次
                                        rotateImg(this, 'right', canvas);
                                        break;
                                }
                            }

                            base64 = canvas.toDataURL("image/jpeg", 0.8);
                        }
                        // else if (navigator.userAgent.match(/Android/i)) {// 修复android
                        //     var encoder = new JPEGEncoder();
                        //     base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth, expectHeight), 80);
                        // }
                        else {
                            if (Orientation != "" && Orientation != 1) {
                                switch (Orientation) {
                                    case 6://需要顺时针（向左）90度旋转
                                        rotateImg(this, 'left', canvas);
                                        break;
                                    case 8://需要逆时针（向右）90度旋转
                                        rotateImg(this, 'right', canvas);
                                        break;
                                    case 3://需要180度旋转
                                        rotateImg(this, 'right', canvas);//转两次
                                        rotateImg(this, 'right', canvas);
                                        break;
                                }
                            }

                            base64 = canvas.toDataURL("image/jpeg", 0.8);
                        }

                        $("img.current").attr("src", base64); //这个就是base64的数据了

                        // $("img.current").attr("src", this.result); //这个就是base64的数据了
                    };
                }
            })(file);
            reader.readAsDataURL(file);

        }

        function showBounce() {
            $('.popUp').css('display', 'block');
        }

        function hideBounce() {
            $('.popUp').css('display', 'none');
        }

        //获取0到max之内的随机数；
        function random(max) {
            var ran = Math.random() * max;

            ran = Math.floor(ran);

            return ran;
        }

        //截图生成图片
        function toPicture() {

            var shareContent = document.getElementById('content');
            var width = shareContent.offsetWidth;
            var height = shareContent.offsetHeight;
            var canvas = document.createElement("canvas");
            var scale = 2;

            canvas.width = width * scale;
            canvas.height = height * scale;
            canvas.getContext("2d").scale(scale, scale);

            var opts = {
                scale: scale,
                canvas: canvas,
                useCORS: true,
                width: width,
                height: height
            };
            html2canvas(shareContent, opts).then(function (canvas) {

                var tupian = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
                localStorage.imgUrl = tupian.src;
                location.href = "./result.html";

            });


        }

        //对图片旋转处理 added by lzk
        function rotateImg(img, direction, canvas) {
            //最小与最大旋转方向，图片旋转4次后回到原方向  
            var min_step = 0;
            var max_step = 3;
            //var img = document.getElementById(pid);  
            if (img == null) return;
            //img的高度和宽度不能在img元素隐藏后获取，否则会出错  
            var height = img.height;
            var width = img.width;
            //var step = img.getAttribute('step');  
            var step = 2;
            if (step == null) {
                step = min_step;
            }
            if (direction == 'right') {
                step++;
                //旋转到原位置，即超过最大值  
                step > max_step && (step = min_step);
            } else {
                step--;
                step < min_step && (step = max_step);
            }

            //旋转角度以弧度值为参数  
            var degree = step * 90 * Math.PI / 180;
            var ctx = canvas.getContext('2d');
            switch (step) {
                case 0:
                    canvas.width = width;
                    canvas.height = height;
                    ctx.drawImage(img, 0, 0);
                    break;
                case 1:
                    canvas.width = height;
                    canvas.height = width;
                    ctx.rotate(degree);
                    ctx.drawImage(img, 0, -height);
                    break;
                case 2:
                    canvas.width = width;
                    canvas.height = height;
                    ctx.rotate(degree);
                    ctx.drawImage(img, -width, -height);
                    break;
                case 3:
                    canvas.width = height;
                    canvas.height = width;
                    ctx.rotate(degree);
                    ctx.drawImage(img, -width, 0);
                    break;
            }
        }

    })
</script>

</html>